package civicinity.ist.psu.edu.events;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import civicinity.ist.psu.edu.CivicinityMainpage;
import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.databases.CivicinityDatabase;
import civicinity.ist.psu.edu.share.CivicinityMyView;
import civicinity.ist.psu.edu.utils.MyLocation;
import civicinity.ist.psu.edu.utils.UploadHandler;
import civicinity.ist.psu.edu.utils.MyLocation.LocationResult;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class CivicinityEventParticipate extends Activity {

	private CivicinityDatabase mDB;
	private String mImagePath;
	private ImageView photoImg;
	private Button uploadBtn;
	private Button revertBtn;
	
	private int mEventID = 0;
	private double mLatitude = 0.0;
	private double mLongitude = 0.0;
	private float mAccuracy = 0;
	
	protected static final int MAX_IMAGE_WIDTH = 1280;
	protected static final int MAX_IMAGE_HEIGHT = 960;
	private Bitmap scaledImage;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.event_participate);
	    
	    Intent gIntent = getIntent();
	    mImagePath = gIntent.getExtras().getString("image_path");
	    mEventID = gIntent.getExtras().getInt("event_id");
	    
	    Log.i("K", "mEventID : " + mEventID);
	    
	    mDB = new CivicinityDatabase(this);

	    MyLocation myLocation = new MyLocation();
	    myLocation.getLocation(this, locationResult);
	    
	    if(mImagePath == null) {
	    	Toast.makeText(this, "Error in fetching a photo", Toast.LENGTH_SHORT).show();
	    	finish();
	    }
	    
	    photoImg = (ImageView)findViewById(R.id.photo);
	    uploadBtn = (Button)findViewById(R.id.upload);
	    revertBtn = (Button)findViewById(R.id.revert);
	    
		File checkExistFile = new File(mImagePath);
		if(checkExistFile.exists()) {
			//speciesImage.
			Bitmap resizedPhoto = ShowPhotoTaken(mImagePath);
			//photoImg.setImageBitmap(overlay(resizedPhoto));
			photoImg.setImageBitmap(resizedPhoto);
		}
		else {
			Toast.makeText(this, "Error in fetching a photo", Toast.LENGTH_SHORT).show();
		}
		
		uploadBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mLatitude == 0.0 || mLongitude == 0.0) {
					Toast.makeText(CivicinityEventParticipate.this, "Please wait while finding your location", Toast.LENGTH_SHORT).show();
				}
				else {
					//Toast.makeText(CivicinityEventParticipate.this, "Successfully added", Toast.LENGTH_SHORT).show();
					
					long timeInMillis = System.currentTimeMillis();
					//int returnID = mDB.setShareMe(mImagePath, Constants.SHARE_CATEGORY[mSelectedItem], commentTxt.getText().toString(), timeInMillis, mLatitude, mLongitude, mAccuracy);
					
					finish();
					Intent intent = new Intent(CivicinityEventParticipate.this, CivicinityEvents.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					
					// upload the values to the server.
					Toast.makeText(CivicinityEventParticipate.this, "Uploading the photo", Toast.LENGTH_SHORT).show();
					UploadHandler upload = new UploadHandler(CivicinityEventParticipate.this);
					upload.uploadEvent(mEventID, mLatitude, mLongitude, mAccuracy, mImagePath);
				}				
			}
		});
		
		revertBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	public LocationResult locationResult = new LocationResult() {

		@Override
		public void gotLocation(Location location) {
			// TODO Auto-generated method stub
			mLatitude = location.getLatitude();
			mLongitude = location.getLongitude();
			mAccuracy = location.getAccuracy();
			
			Log.i("K", "Accuracy : " + mAccuracy);
		}
	};
	
	public Bitmap ShowPhotoTaken(String path) {
		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, options);
			
			int factor =  Math.max(options.outWidth / MAX_IMAGE_WIDTH, options.outHeight / MAX_IMAGE_HEIGHT);
			
			options.inSampleSize = msb32(factor);
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			
			Bitmap image = BitmapFactory.decodeFile(path, options);
			
			
			if(image.getWidth() > MAX_IMAGE_WIDTH || image.getHeight() > MAX_IMAGE_HEIGHT) {
				float scale = Math.min(MAX_IMAGE_WIDTH / (float)image.getWidth(), 
						MAX_IMAGE_HEIGHT / (float)image.getHeight());
				
				int newWidth = (int)((image.getWidth() * scale) + 0.5f);
				int newHeight = (int)((image.getHeight() * scale) + 0.5f);
				
				scaledImage = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);
				image.recycle();	
			}
			else {
				scaledImage = image;
			}
			
			OutputStream os = new FileOutputStream(path);
			scaledImage.compress(CompressFormat.JPEG, 80, os);
			os.close();
			
			int width = scaledImage.getWidth();
		   	int height = scaledImage.getHeight();
		   	
		    Bitmap resized_bitmap = null;
		    // set new width and height of the phone_image
		    int new_width = 250;
		    int new_height = 250;
		   	
		   	float scale_width = ((float) new_width) / width;
		   	float scale_height = ((float) new_height) / height;
		   	Matrix matrix = new Matrix();
		   	matrix.postScale(scale_width, scale_height);
		   	resized_bitmap = Bitmap.createBitmap(scaledImage, 0, 0, width, height, matrix, true);
			
		   	return resized_bitmap;
			
		}
		catch(FileNotFoundException e){
			
		}
		catch(IOException e) {
			
		}
		catch(OutOfMemoryError e){
			
		}
		return null;
	}
	
    private int msb32(int x) {
        x |= (x >> 1);
        x |= (x >> 2);
        x |= (x >> 4);
        x |= (x >> 8);
        x |= (x >> 16);
        return (x & ~(x >> 1));
    }

}
